import requests
import json
from base.setting import setting
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from base import loginfo
import socket
socket.setdefaulttimeout(20)
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


class ApiRequests:
    """
    请求类,对请求的方法，数据的处理，主要json数据类型
    """

    def __init__(self, header=None):
        self.header = json.loads(setting.env['header'])
        if header:
            self.header.update(header)

    def post_main(self, url, data):
        return requests.post(url=url, data=data, headers=self.header, verify=False)

    def get_main(self, url):
        return requests.get(url=url, headers=self.header, verify=False)

    def run_main(self, url, data=None, flag=True, method='post'):
        """
        :param url: 接口地址
        :param data: 请求数据
        :param flag: 是否执行
        :param method: 请求方式
        :return: 结果数据
        """
        url = setting.env['domain'] + url
        if flag:
            # 进行编码处理
            if method.lower() == 'get':
                res = self.get_main(url)
            else:
                loginfo.debug('请求参数: \n\t\t\t\t\t\t{}'.format(data))
                res = self.post_main(url, json.dumps(data))
            return res.content.decode('utf-8')
